layui.define(['setter', 'table', 'form', 'laydate'], function (experts) {
    var $ = layui.$
        , form = layui.form
        , laydate = layui.laydate
        , table = layui.table;


    var search = function (options) {

        //默认的查询条件
        var defaultWhere = options.where;

        //检查这个字段是否启用了查询
        function fieldIsSearch(field) {
            var search = field.search;

            if (search == undefined) {
                return false;
            }

            if (typeof (search) == "boolean" && search == false) {
                return false;
            }

            return true;
        }

        //检查表格是否开启查询
        function enabledSearch() {
            var isSearch = false;
            options.cols[0].forEach(function (row) {
                if (fieldIsSearch(row)) {
                    isSearch = true;
                }
            });

            return isSearch;
        }

        //获取所有要查询的字段
        function getSearchFields() {
            var arr = new Array();

            options.cols[0].forEach(function (row) {
                if (fieldIsSearch(row)) {

                    var field = $.extend(true, {}, {
                        title: row.title,
                        field: row.field,
                        order: 100
                    }, row.search);

                    arr.push(field);
                }
            });

            //排序
            for (i = 0; i < arr.length - 1; i++) {
                for (j = 0; j < arr.length - 1 - i; j++) {

                    var a = arr[j].order == undefined ? 100 : arr[j].order;
                    var b = arr[j + 1].order == undefined ? 100 : arr[j + 1].order;

                    if (a > b) {
                        var temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                    }
                }
            }

            return arr;
        }

        function getSearchFieldsHTML() {
            var html = "<div class='layui-fluid'><form class='layui-form' id='search-form-" + options.id + "' lay-filter='searchForm'>";

            var searchCount = 0;

            var fields = getSearchFields();

            fields.forEach(function (field) {
                var input = "";
                switch (field.type) {
                    case "radio" :
                        input = searchWays.radio(field);
                        break;
                    case "select" :
                        input = searchWays.select(field);
                        break;
                    case "date" :
                    case "date-range" :
                        input = searchWays.date(field, field.type);
                        break;
                    case "datetime" :
                        input = searchWays.datetime(field, field.type);
                        break;
                    default:
                        input = searchWays.text(field);
                        break;
                }
                ;

                var item = "<div class=\"layui-form-item\">" +
                    "<label class=\"layui-form-label\">" + field.title + "</label>" +
                    "<div class=\"layui-input-block\">" +
                    input +
                    "</div>" +
                    "</div>";

                html += item;
                searchCount++;
            });

            if (searchCount == 0) {
                html += "未设置查询条件";
            }

            html += "</form></div>";

            var data = {
                html: html,
                height: searchCount * 48 + 170
            };

            return data;
        }

        //查询条件缓存
        var whereCache = null;

        function getSearchData() {
            var searchFields = $("#search-form-" + options.id + " .search-field");

            var data = {};

            //设置到第一页
            searchFields.each(function () {
                var field = $(this);
                var key = field.attr("field");

                //默认设置为null，以防多次查询时，layui还保留了上次查询的字段
                var value = null;

                //如果是清除条件，则所有字段设置为null
                if (this.tagName == "INPUT") {

                    switch (this.type.toUpperCase()) {
                        case "TEXT":
                            var v = field.val().trim();
                            if (v.length > 0) {
                                value = field.val().trim();
                            }
                            break;
                        case "RADIO":
                            //取这个单选组的值
                            var items = document.getElementsByName(this.name);
                            for (var i = 0; i < items.length; i++) {
                                var item = items[i];
                                if (item.checked) {
                                    value = item.value;
                                }
                            }
                            break;
                    }
                } else if (this.tagName == "SELECT") {
                    if (this.value) {
                        value = field.val();
                    }
                }
                data[key] = value;

            });

            var hasWhere = false;

            for (var i in data) {
                hasWhere = true;
                break;
            }

            if (hasWhere) {
                whereCache = data;
                return data;
            } else {
                return null;
            }
        }

        function reloadTable(where) {
            //执行查询
            table.reload(options.id, {
                where: where,
                page: {curr: 1},
                done: function () {
                }
            });
        }

        var searchWays = {
            text: function (field) {
                return "<input type='text' field='" + field.field + "' maxlength='50' autocomplete='off' class='layui-input search-field'>";
            },
            radio: function (field) {
                var str = "";
                var items = field.items;
                if (items == undefined || items == null || items == 0) {
                    alert("error:查询字段" + field.title + " 类型为radio，但未设置items属性");
                }
                items.forEach(function (item) {
                    str += "<input type='radio' field='" + field.field + "' class='search-field' name='search_radio_" + field.field + "' value='" + item.value + "' title='" + item.text + "'>";
                });

                return str;
            },
            select: function (field) {
                var select = "<select field='" + field.field + "' class='search-field'>";
                select += "<option value=''>请选择</option>";

                var items = field.items;
                if (items == undefined || items == null || items == 0) {
                    alert("error:查询字段" + field.title + " 类型为select，但未设置items属性");
                }
                items.forEach(function (item) {
                    select += "<option value='" + item.value + "'>" + item.text + "</option>";
                });

                select += "</select>";

                return select;
            },
            date: function (field, dateRange) {
                return "<input type='text' data-type='date' date='" + dateRange + "' readonly field='" + field.field + "' autocomplete='off' class='layui-input search-date search-field'>";
            },
            datetime: function (field) {
                return "<input type='text' data-type='datetime' field='" + field.field + "' class='layui-input search-datetime search-field'>";
            }
        };

        this.init = function () {

            if (!enabledSearch()) {
                return;
            }

            var bar = $("<div class='table-search'>");

            var functionName = new Date().getTime();

            var btn = "<div onclick='open" + functionName + "()' class='layui-inline' title='高级查询' lay-event='search'><i class='layui-icon layui-icon-search'></i></div>";
            var clear = "<div onclick='clear" + functionName + "()' class='layui-inline' title='清除查询条件' lay-event='search-clear'><i class='layui-icon layui-icon-fonts-clear'></i></div>";
            var refresh = "<div onclick='refresh" + functionName + "()' class='layui-inline' title='刷新' lay-event='search-clear'><i class='layui-icon layui-icon-refresh'></i></div>";

            bar.append(refresh);
            bar.append(btn);
            bar.append(clear);

            //工具栏对象
            var toolbar = null;

            if (typeof (options.toolbar) == "boolean" || options.toolbar == "default") {
                //创建一个
                toolbar = $("<span>");
            } else if (typeof (options.toolbar) == "string") {
                toolbar = $(options.toolbar);
            }

            toolbar.append(bar);

            //注册打开查询窗口事件
            window["open" + functionName] = function () {
                var data = getSearchFieldsHTML();

                layer.open({
                    type: 1,
                    title: "高级查询",
                    shadeClose: true,
                    area: ['500px', data.height + 'px'],
                    content: data.html,
                    btn: ['查询', '重置', '关闭'],
                    yes: function (index, layero) {
                        //执行查询
                        reloadTable(getSearchData());

                        layer.close(index);
                    },
                    btn2: function (index, layero) {
                        document.forms["search-form-" + options.id].reset();
                        return false;
                    },
                    no: function (index, layero) {
                        layer.close(index); //关闭弹层
                    },
                    end: function (index, layero) {
                        // table.reload("table-user-list");
                    },
                    success: function () {
                        form.render(null, 'searchForm');
                        $("#search-form-" + options.id + " .search-date").each(function () {
                            laydate.render({
                                elem: this
                                , range: $(this).attr("date") == "date-range" ? "至" : false //或 range: '~' 来自定义分割字符
                            });
                        });
                        $("#search-form-" + options.id + " .search-datetime").each(function () {
                            laydate.render({
                                elem: this
                                , type: "datetime"
                                , fullPanel: true
                            });
                        });
                    }
                }, function (value, index) {
                    layer.close(index);
                });
            }

            //清除查询条件
            window["clear" + functionName] = function () {
                if (defaultWhere == undefined) {
                    defaultWhere = null;
                } else {
                    var fields = getSearchFields();
                    fields.forEach(function (field) {
                        defaultWhere[field.field] = null;
                    });
                }

                reloadTable(defaultWhere);
            }

            //刷新
            window["refresh" + functionName] = function () {
                reloadTable();
            }
        };

        // this.getValue = function () {
        //     var value = "";
        //
        //     $("." + id).each(function () {
        //         value += this.value;
        //     });
        //
        //     return value;
        // }
    };


    experts("tableSearch", {
        render: function (options) {
            //未打开工具条
            if (options.toolbar == undefined || options.toolbar.length == 0 || options.toolbar == false) {
                return;
            }

            // options.cols
            var searchBar = new search(options);

            searchBar.init();
        }
    })
});